package com.soywer.rpc.rpc02;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

import com.soywer.rpc.common.User;

/**
 * 功能描述：
 * 相对于rpc01，改进的地方在于增加了一个客户端的代理，将socket连接服务端的代码隐藏了起来；
 * @author 18065916_李猛
 * @since 2021/3/8
 */
public class Stub {
    public User findUserById(Integer id) throws Exception{
        Socket s = new Socket("127.0.0.1",8888);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeInt(id);

        s.getOutputStream().write(baos.toByteArray());
        s.getOutputStream().flush();

        DataInputStream dis = new DataInputStream(s.getInputStream());
        int receiveId = dis.readInt();
        String name = dis.readUTF();
        User user = new User(receiveId , name);

        dos.close();
        s.close();
        return user;
    }
}
